<template>
    <div class="rbac-container">
    <el-container>
      <el-header class="search-header">
        <el-form :inline="true" :model="query" class="search-form">
        <el-form-item label="用户名称">
          <el-input v-model="query.NickName" placeholder="请输入用户名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
          <el-button type="success" @click="open(null)" :icon="Plus">新增</el-button>
          <el-button type="primary" @click="Export" :icon="Plus">导出</el-button>
        </el-form-item>
      </el-form>
      </el-header>
      <el-main class="data-main">
           <el-table :data="tableData" class="data-table" :border="true" :stripe="true" v-loading="loading" element-loading-text="数据加载中...">
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="password" label="密码" width="100px">
                <template v-slot="scoped">
                    <span>******</span>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名"/>
              <el-table-column prop="roleName" label="角色"/>
              <el-table-column prop="userState" label="是否启用" width="100px" align="center">
                    <template v-slot="scoped">
                         <el-switch
                            v-model="scoped.row.userState"
                            inline-prompt
                            active-text="启用"
                            inactive-text="禁用"
                            @change="updateState(scoped.row)"
                          />
                    </template>
              </el-table-column>
              <el-table-column type="index" label="序号" width="80px" align="center"/>
              <el-table-column prop="createTime" label="创建时间" width="180px">
                <template v-slot="scoped">
                    <span>{{moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss")}}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="180px" align="center">
                <template v-slot="scoped">
                  <el-button link type="danger" size="small" @click="deleteRole(scoped.row)" :icon="Delete">删除</el-button>
                  <el-button link type="primary" size="small" @click="open(scoped.row)" :icon="Edit">修改</el-button>
                </template>
              </el-table-column>
            </el-table>
            
             <el-pagination
             class="pagination"
              v-model:current-page="page.PageIndex"
              v-model:page-size="page.PageSize"
              :page-sizes="[3, 5, 8]"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              prev-text="上一页"
              next-text="下一页"
              :total="page.totalCount"
            />

            <el-dialog v-model="logic.isopen" :title="logic.title" width="600" destroy-on-close center class="custom-dialog">
              <el-form
                  ref="ruleFormRef"
                  class="custom-form"
                  :model="ruleForm"
                  :rules="rules"
                  label-width="120"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="ruleForm.username" placeholder="请输入用户名" />
                  </el-form-item>
                  <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" show-password placeholder="请输入密码"/>
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入姓名" />
                  </el-form-item>
                  <el-form-item label="是否启用" prop="userState">
                        <el-switch v-model="ruleForm.userState" active-color="#13ce66" inactive-color="#ff4949" />
                </el-form-item>
                  <el-form-item label="角色" prop="roleId">
                    <el-checkbox-group v-model="ruleForm.roleId" class="permission-checkbox-group">
                        <el-checkbox v-for="item in roles" :key="item.id" :value="item.id" name="type" class="permission-checkbox">
                            {{item.roleName}}
                        </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item class="form-buttons">
                    <el-button type="primary" @click="submitForm(ruleFormRef)" :icon="Check">
                      保存
                    </el-button>
                    <el-button @click="logic.isopen=false" :icon="Close">返回</el-button>
                  </el-form-item>
                </el-form>
            </el-dialog>
      </el-main>
    </el-container>
  </div>
 
</template>

<script lang="ts" setup>
import { getUser,addUser,updateUser,deleteUser,getALLRole,updateUserState } from '@/Https/server';
import { onMounted, ref,reactive, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import moment from 'moment';
import { Search, Plus, Edit, Delete, Check, Close } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/counter';
const store = useCounterStore();
onMounted(()=>{
    // 使用nextTick确保DOM渲染完成后再加载数据
    nextTick(() => {
        GetUser();
    });
})
//查询条件
const query =reactive({
    NickName:''
})
const page =reactive({
    PageIndex:1,
    PageSize:3,
    totalCount:0,
    pageCount:0
})
//侦听器
watch(page,()=>
{
  GetUser();

},{deep:true})


//查询方法 - 添加防抖
let searchTimer: NodeJS.Timeout | null = null;
const onSubmit = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  // 设置新的定时器，300ms后执行搜索
  searchTimer = setTimeout(() => {
    GetUser();
  }, 300);
}
//加载用户
const tableData = ref<any>([]);
const loading = ref(false); // 添加加载状态
const lastQuery = ref(''); // 缓存上次查询条件

const GetUser=()=>{
    // 检查是否需要重新加载（查询条件或分页发生变化）
    const currentQuery = JSON.stringify({
        NickName: query.NickName,
        PageIndex: page.PageIndex,
        PageSize: page.PageSize
    });
    
    // 如果查询条件没有变化且已有数据，则不重新加载
    if (currentQuery === lastQuery.value && tableData.value.length > 0) {
        return;
    }
    
    loading.value = true; // 开始加载
    lastQuery.value = currentQuery; // 更新缓存
    
    getUser({NickName:query.NickName,
            PageIndex:page.PageIndex,
            PageSize:page.PageSize})
    .then((res:any)=>{
        tableData.value=res.data.pageData;
        page.totalCount = res.data.totalCount;
        page.pageCount = res.data.pageCount;
    })
    .catch((error) => {
        console.error('获取用户数据失败:', error);
        ElMessage.error('获取数据失败，请稍后重试');
    })
    .finally(() => {
        loading.value = false; // 结束加载
    });
}
//逻辑参数
const logic = reactive({
   isopen:false,
   isAdd:false,
   title:'',
})

//加载角色
const roles = ref<any>([]);
const roleLoading = ref(false); // 添加角色加载状态

const GetRoleList=()=>{
    roleLoading.value = true; // 开始加载
    getALLRole()
    .then((res:any)=>{
        roles.value=res.data;
    })
    .catch((error) => {
        console.error('获取角色数据失败:', error);
        ElMessage.error('获取角色数据失败，请稍后重试');
    })
    .finally(() => {
        roleLoading.value = false; // 结束加载
    });
}
//---------------导出---------------------//
const Export=()=>{
  location.href="http://localhost:5062/api/Login/Export"
}

//#region  增删改

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "id": 0,
  "username": "",
  "password": "",
  "name": "",
  "createId": 0,
  "createTime": "",
  "userState": true,
  "roleId": []
})
//数据验证
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
  ],
   password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
   name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
  ],
   roleId: [
    { required: true, message: '必须选择至少一个角色', trigger: 'blur' },
  ],
})
//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(logic.isAdd==true)
      {
          addUser(ruleForm)
          .then((res:any)=>{
            if(res.code==200){
              logic.isopen =false;
              GetUser();
              ElMessage.success(res.message);
            }else{
              ElMessage.error(res.message);
            }
          })
      }
      else
      {
        updateUser(ruleForm)
        .then((res:any)=>{
          if(res.code==200){
            logic.isopen =false;
            GetUser();
            store.getMenus();
            ElMessage.success(res.message);
          }else{
            ElMessage.error(res.message);
          }
        })
      }
      
    } else {
      console.log('error submit!', fields)
    }
  })
}
//打开方法
const open =(row:any)=>{
  logic.isopen=true;
  GetRoleList();
  if(row==null)
  {
      logic.isAdd =true;
      logic.title="新增用户"
      ruleForm.id =0;
      ruleForm.name ='';
      ruleForm.password = '';
      ruleForm.username='';
      ruleForm.userState=false;
      ruleForm.roleId=[];
  }
  else
  {
    console.log(row);
      logic.isAdd =false;
      logic.title="修改用户"
      ruleForm.id =row.id;
      ruleForm.name =row.name;
      ruleForm.password = row.password;
      ruleForm.username=row.username;
      ruleForm.userState=row.userState;
      ruleForm.roleId=row.roleId;
      ruleForm.createId = row.createId;
      ruleForm.createTime =row.createTime;
  }
}
//删除
const deleteRole=(row:any)=>{
   ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      if(row.userState==true)
      {
        ElMessage.error("用户账号使用中，无法删除");
        return;
      }
        deleteUser(row).then((res:any)=>{
          if(res.code==200)
          {
            GetUser();
            ElMessage.success(res.message);
          }
          else
          {
            ElMessage.error(res.message);
          }
        })
    })
  
}
//修改状态
const updateState=(row:any)=>{
  updateUserState(row).then((res:any)=>{
    if(res.code==200)
    {
      GetUser();
      ElMessage.success(res.message);
    }
    else
    {
      GetUser();
      ElMessage.error(res.message);
    }
  })
}
//#endregion

</script>

<style>
.rbac-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.search-header {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.data-main {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  min-height: 500px;
}

.data-table {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.custom-dialog .el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.custom-form {
  padding: 20px 0;
}

.form-buttons {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

/* 维持Element Plus输入框和选择框的宽度 */
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.permission-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.permission-checkbox {
  width: 180px;
  height: 45px;
  margin: 5px;
  background-color: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  padding: 0 15px;
  box-sizing: border-box;
}

.permission-checkbox .el-checkbox__label {
  font-size: 14px;
}

.permission-checkbox.is-checked {
  background-color: #ecf5ff;
  border-color: #409eff;
}

</style>